﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TBR.Common
{
    public class HtmlHelper
    {
        public IList<string> GetDivCollections(string htmlCode, string beforeText, string afterText, string beforeSeparator, string afterSeparator, Tag beforeTag = Tag.Div, Tag afterTag = Tag.Div)
        {
            htmlCode = GetHtml(htmlCode, beforeText, afterText, beforeTag, afterTag);
            return htmlCode.Replace(beforeSeparator + afterSeparator, beforeSeparator + "#" + afterSeparator).Split(new char[] { '#' }).ToList();
        }

        public string GetHtml(string htmlCode, string beforeText, string afterText, Tag beforeTag = Tag.Div, Tag afterTag = Tag.Div)
        {
            string textBeforeTag = String.Empty, textAfterTag = String.Empty;
            switch (beforeTag)
            {
                case Tag.Div: textBeforeTag = "</div>";
                    break;
                case Tag.TwoDivs: textBeforeTag = "</div>\n</div>";
                    break;
                case Tag.Form: textBeforeTag = "</form>";
                    break;
            }
            switch (afterTag)
            {
                case Tag.Div: textAfterTag = "<div";
                    break;
                case Tag.TwoDivs: textAfterTag = "<div><div";
                    break;
                case Tag.Form: textAfterTag = "<form";
                    break;
            }
            try
            {
                var b = htmlCode.Remove(0, htmlCode.IndexOf(beforeText));
                htmlCode = b.Remove(0, b.IndexOf(textBeforeTag) + textBeforeTag.Length);
                var c = htmlCode.Substring(0, htmlCode.IndexOf(afterText));
                htmlCode = c.Substring(0, c.LastIndexOf(textAfterTag));
                return htmlCode.Replace("\t", "").Replace("\n", "").Replace("\r", "").Replace("  ", "");
            }
            catch { return null; }
        }

        public enum Tag
        {
            Div = 0,
            Form = 1,
            TwoDivs = 2
        }
    }
}
